package main

import (
	"flag"
	"log"
	"os"
	"runtime/pprof"
	"wrench/cmds"
	"wrench/config"
)

func main() {

	var (
		confFile     string
		command      string
		hostFile     string
		hostFilter   string
		groupName    string
		templateFile string
		level        string
	)

	var cpuProfile = flag.String("cpuProfile", "", "记录CPU使用情况到文件")
	var pingHost = flag.Bool("ping", false, "只判断主机是否可达")
	var console = flag.Bool("console", false, "控制台模式")
	var cache = flag.Bool("C", false, "清除此次执行缓存")
	flag.StringVar(&confFile, "f", "", "指定配置文件")
	flag.StringVar(&hostFile, "i", "conf/hosts", "指定主机列表文件")
	flag.StringVar(&groupName, "g", "", "指定主机组,以逗号分隔")
	flag.StringVar(&templateFile, "t", "renderfile", "指定模板文件")
	flag.StringVar(&command, "c", "", "指定命令，以分号做分隔符，覆盖配置文件中的exec模块")
	flag.StringVar(&hostFilter, "r", "", "按主机名做正则过滤，以逗号分隔")
	flag.StringVar(&level, "l", "info", "指定日志级别，< error warn info debug trace >")
	flag.Parse()

	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		err = pprof.StartCPUProfile(f)
		if err != nil {
			log.Fatal(err)
		}
		defer pprof.StopCPUProfile()
	}
	config.WeCome()
	var cf = config.ParseConf(&confFile, &hostFile, groupName, hostFilter, level)

	SyncWaitGroupChannel := config.SyncWaitGroupChannelType{}
	cmds.SetSyncWaitGroupChannel(cf, &SyncWaitGroupChannel)

	if command != "" {
		cf.Task[0] = config.Task{
			Shell: []config.Shell{{
				Name: "cmd",
				Sudo: false,
				Cmd:  cmds.CmdSpilt(command, ";")},
			},
		}
		cf.Task = cf.Task[0:1]
	} else if *pingHost {
		cmds.PingHost(cf, &SyncWaitGroupChannel)
		return
	} else if *console {
		cmds.ConsoleCmd(cf, &SyncWaitGroupChannel)
		return
	}

	for _, t := range cf.Task {
		cmds.OrderTask(&t, cf, &SyncWaitGroupChannel)
	}

	if !*cache {
		config.DeleteCacheFile()
	}

}
